<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="24" class="stats-cards">
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="stat-icon total-requests">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatNumber(stats?.totalRequests || 0) }}</div>
            <div class="stat-label">总请求数</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="stat-icon total-traffic">
            <el-icon><Upload /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatBytes(stats?.totalTraffic || 0) }}</div>
            <div class="stat-label">总流量</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="stat-icon success-rate">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ formatPercent(stats?.successRate || 0) }}</div>
            <div class="stat-label">成功率</div>
          </div>
        </div>
      </el-col>
      
      <el-col :xs="24" :sm="12" :lg="6">
        <div class="stat-card">
          <div class="stat-icon online-proxies">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-number">{{ stats?.onlineProxies || 0 }}/{{ stats?.totalProxies || 0 }}</div>
            <div class="stat-label">在线代理</div>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 图表区域 -->
    <el-row :gutter="24" class="charts-section">
      <!-- 流量趋势图 -->
      <el-col :xs="24" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>流量趋势</span>
              <el-select v-model="trafficDays" size="small" @change="loadTrafficData">
                <el-option label="最近7天" :value="7" />
                <el-option label="最近15天" :value="15" />
                <el-option label="最近30天" :value="30" />
              </el-select>
            </div>
          </template>
          <div ref="trafficChartRef" class="chart-container" />
        </el-card>
      </el-col>
      
      <!-- 代理使用分布 -->
      <el-col :xs="24" :lg="8">
        <el-card class="chart-card">
          <template #header>
            <span>代理使用分布</span>
          </template>
          <div ref="proxyUsageChartRef" class="chart-container" />
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 实时数据 -->
    <el-row :gutter="24" class="realtime-section">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>实时数据</span>
              <el-tag :type="realtimeConnected ? 'success' : 'danger'">
                {{ realtimeConnected ? '已连接' : '已断开' }}
              </el-tag>
            </div>
          </template>
          
          <el-row :gutter="16">
            <el-col :xs="24" :sm="8">
              <div class="realtime-item">
                <div class="realtime-label">平均响应时间</div>
                <div class="realtime-value">{{ formatResponseTime(stats?.avgResponseTime || 0) }}</div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="8">
              <div class="realtime-item">
                <div class="realtime-label">当前连接数</div>
                <div class="realtime-value">{{ currentConnections }}</div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="8">
              <div class="realtime-item">
                <div class="realtime-label">今日新增流量</div>
                <div class="realtime-value">{{ formatBytes(todayTraffic) }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import {
  TrendCharts,
  Upload,
  CircleCheck,
  Connection
} from '@element-plus/icons-vue'
import { statsApi } from '../api'
import { formatBytes, formatNumber, formatPercent, formatResponseTime } from '../utils'
import type { AccessStats, TrafficData, ProxyUsageData } from '../types'

// 响应式数据
const stats = ref<AccessStats>()
const trafficData = ref<TrafficData[]>([])
const proxyUsageData = ref<ProxyUsageData[]>([])
const trafficDays = ref(7)
const currentConnections = ref(0)
const todayTraffic = ref(0)
const realtimeConnected = ref(false)

// 图表引用
const trafficChartRef = ref<HTMLDivElement>()
const proxyUsageChartRef = ref<HTMLDivElement>()

let trafficChart: echarts.ECharts | null = null
let proxyUsageChart: echarts.ECharts | null = null
let realtimeTimer: NodeJS.Timeout | null = null

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await statsApi.getAccessStats()
    if (response.code === 200) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('Failed to load stats:', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 加载流量数据
const loadTrafficData = async () => {
  try {
    const response = await statsApi.getTrafficData(trafficDays.value)
    if (response.code === 200) {
      trafficData.value = response.data
      updateTrafficChart()
    }
  } catch (error) {
    console.error('Failed to load traffic data:', error)
    ElMessage.error('加载流量数据失败')
  }
}

// 加载代理使用数据
const loadProxyUsageData = async () => {
  try {
    const response = await statsApi.getProxyUsage()
    if (response.code === 200) {
      proxyUsageData.value = response.data
      updateProxyUsageChart()
    }
  } catch (error) {
    console.error('Failed to load proxy usage data:', error)
    ElMessage.error('加载代理使用数据失败')
  }
}

// 初始化流量趋势图表
const initTrafficChart = () => {
  if (!trafficChartRef.value) return
  
  trafficChart = echarts.init(trafficChartRef.value)
  updateTrafficChart()
}

// 更新流量趋势图表
const updateTrafficChart = () => {
  if (!trafficChart || !trafficData.value.length) return
  
  const dates = trafficData.value.map(item => item.date)
  const requests = trafficData.value.map(item => item.requests)
  const traffic = trafficData.value.map(item => item.traffic / 1024 / 1024) // 转换为MB
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: (params: any) => {
        const date = params[0].axisValue
        const request = params[0].value
        const trafficMB = params[1].value
        return `
          <div>
            <div>${date}</div>
            <div>请求数: ${formatNumber(request)}</div>
            <div>流量: ${trafficMB.toFixed(2)} MB</div>
          </div>
        `
      }
    },
    legend: {
      data: ['请求数', '流量(MB)']
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false
    },
    yAxis: [
      {
        type: 'value',
        name: '请求数',
        position: 'left',
        axisLabel: {
          formatter: (value: number) => formatNumber(value)
        }
      },
      {
        type: 'value',
        name: '流量(MB)',
        position: 'right',
        axisLabel: {
          formatter: (value: number) => value.toFixed(1) + 'MB'
        }
      }
    ],
    series: [
      {
        name: '请求数',
        type: 'line',
        data: requests,
        smooth: true,
        itemStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
            { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
          ])
        }
      },
      {
        name: '流量(MB)',
        type: 'line',
        yAxisIndex: 1,
        data: traffic,
        smooth: true,
        itemStyle: {
          color: '#52c41a'
        }
      }
    ],
    grid: {
      left: '50px',
      right: '50px',
      bottom: '50px',
      top: '50px'
    }
  }
  
  trafficChart.setOption(option)
}

// 初始化代理使用分布图表
const initProxyUsageChart = () => {
  if (!proxyUsageChartRef.value) return
  
  proxyUsageChart = echarts.init(proxyUsageChartRef.value)
  updateProxyUsageChart()
}

// 更新代理使用分布图表
const updateProxyUsageChart = () => {
  if (!proxyUsageChart || !proxyUsageData.value.length) return
  
  const data = proxyUsageData.value.map(item => ({
    name: item.proxyName,
    value: item.requests
  }))
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const item = proxyUsageData.value.find(p => p.proxyName === params.name)
        if (item) {
          return `
            <div>
              <div>${item.proxyName}</div>
              <div>请求数: ${formatNumber(item.requests)}</div>
              <div>流量: ${formatBytes(item.traffic)}</div>
              <div>成功率: ${formatPercent(item.successRate)}</div>
            </div>
          `
        }
        return ''
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          formatter: '{b}\n{d}%'
        }
      }
    ]
  }
  
  proxyUsageChart.setOption(option)
}

// 模拟实时数据更新
const startRealtimeUpdate = () => {
  realtimeConnected.value = true
  
  realtimeTimer = setInterval(() => {
    // 模拟实时数据
    currentConnections.value = Math.floor(Math.random() * 100) + 50
    todayTraffic.value = Math.floor(Math.random() * 1024 * 1024 * 100) + 1024 * 1024 * 500
  }, 3000)
}

// 停止实时数据更新
const stopRealtimeUpdate = () => {
  if (realtimeTimer) {
    clearInterval(realtimeTimer)
    realtimeTimer = null
  }
  realtimeConnected.value = false
}

// 处理窗口大小变化
const handleResize = () => {
  if (trafficChart) {
    trafficChart.resize()
  }
  if (proxyUsageChart) {
    proxyUsageChart.resize()
  }
}

// 生命周期
onMounted(async () => {
  // 加载数据
  await Promise.all([
    loadStats(),
    loadTrafficData(),
    loadProxyUsageData()
  ])
  
  // 初始化图表
  setTimeout(() => {
    initTrafficChart()
    initProxyUsageChart()
  }, 100)
  
  // 开始实时数据更新
  startRealtimeUpdate()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理资源
  stopRealtimeUpdate()
  
  if (trafficChart) {
    trafficChart.dispose()
  }
  if (proxyUsageChart) {
    proxyUsageChart.dispose()
  }
  
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

/* 统计卡片样式 */
.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.total-requests {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.total-traffic {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.success-rate {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.online-proxies {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #7f8c8d;
}

/* 图表区域样式 */
.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  height: 400px;
}

.chart-card :deep(.el-card__body) {
  height: calc(100% - 57px);
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  width: 100%;
  height: 100%;
}

/* 实时数据样式 */
.realtime-section {
  margin-bottom: 24px;
}

.realtime-item {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 16px;
}

.realtime-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.realtime-value {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stat-card {
    padding: 16px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 20px;
    margin-right: 12px;
  }
  
  .stat-number {
    font-size: 24px;
  }
  
  .chart-card {
    height: 300px;
  }
  
  .realtime-value {
    font-size: 20px;
  }
}
</style>